import fs from 'fs'
import path from 'path'

const { readdir, rm } = fs.promises

/**
 * 格式化文件名
 * @param targetDir
 */
export function formatTargetDir (targetDir: string): string {
  return targetDir?.trim().replace(/\/+$/g, '')
}

/**
 * 文件是否为空文件
 * @param path
 */
export function isEmpty (path: string): boolean {
  if (!fs.existsSync(path)) return true
  const files = fs.readdirSync(path)
  return files.length === 0 || (files.length === 1 && files[0] === '.git')
}

/**
 * 删除文件
 * @param input
 * @param options
 */
export const remove: typeof rm = async (input, options) => {
  await rm(input, { recursive: true, force: true, ...options })
}

/**
 * 清空文件
 * @param dir
 */
export async function emptyDir (dir: string): Promise<void> {
  if (!fs.existsSync(dir)) return
  const files = await readdir(dir)
  for (const file of files) {
    await remove(path.resolve(dir, file))
  }
}
